//
//  Panda.swift
//  MySpriteKit
//
//  Created by haogaoming on 16/9/9.
//  Copyright © 2016年 郝高明. All rights reserved.
//

import SpriteKit

enum Status: Int {
    case run=1,jump,jump2,roll;
}

class Panda: SKSpriteNode {
    //熊猫跑动资源
    let runAtlas = SKTextureAtlas(named: "run.atlas")
    //熊猫跑动数组
    var runFrames = [SKTexture]()
    
    //熊猫跳资源
    let jumpAtlas = SKTextureAtlas(named: "jump.atlas")
    //熊猫跳动数组
    var jumpFrames = [SKTexture]()
    
    //熊猫打滚动资源
    let rollAtlas = SKTextureAtlas(named: "roll.atlas")
    //熊猫打滚数组
    var rollFrames = [SKTexture]()
    
    //熊猫当前运动状态
    var status = Status.run
    
    init(){
        let texture = runAtlas.textureNamed("panda_run_01")
        let size = texture.size()
        super.init(texture: texture, color: UIColor.whiteColor(), size: size)
        
        //熊猫run资源
        for i in 1...(runAtlas.textureNames.count) {
            let tempName = "panda_run_0\(i)"
            let runTexture:SKTexture? = runAtlas.textureNamed(tempName)
            if runTexture != nil {
                runFrames.append(runTexture!)
            }
        }
        
        //熊猫jump资源
        for i in 1...(jumpAtlas.textureNames.count) {
            let tempName = "panda_jump_0\(i)"
            let jumpTexture:SKTexture? = jumpAtlas.textureNamed(tempName)
            if jumpTexture != nil {
                jumpFrames.append(jumpTexture!)
            }
        }
        
        //熊猫roll资源
        for i in 1...(rollAtlas.textureNames.count) {
            let tempName = "panda_roll_0\(i)"
            let rollTexture:SKTexture? = rollAtlas.textureNamed(tempName)
            if rollTexture != nil {
                rollFrames.append(rollTexture!)
            }
        }
        
        //跑
        run()
    }
    
    //跑的函数
    func run() {
        //移除所有状态
        removeAllActions()
        status = .run
        runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(runFrames, timePerFrame: 0.05)))
    }
    
    //跳函数
    func jump() {
        //移除所有状态
        removeAllActions()
        status = .jump
        
        runAction(SKAction.animateWithTextures(jumpFrames, timePerFrame: 0.05))
    }
    
    //滚动函数
    func roll() {
        //移除所有状态
        removeAllActions()
        status = .roll
        
        //滚完后，接着跑
        runAction(SKAction.animateWithTextures(rollFrames, timePerFrame: 0.05),completion:{() in
            self.run()
        })
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
